# -*- coding: utf-8 -*-

# Define your item pipelines here

from sqlalchemy.orm import sessionmaker
from bili_spider.models import BiliDB, db_connect, create_table
import json


class BiliSpiderPipeline(object):
    def __init__(self):
        """
        Initializes database connection and sessionmaker.
        Creates deals table.
        """
        engine = db_connect()
        create_table(engine)
        self.Session = sessionmaker(bind=engine)

    def process_item(self, item, spider):
        """Save deals in the database.

        This method is called for every item pipeline component.
        """
        session = self.Session()
        db = BiliDB()
        db.url = item["url"]
        db.anime_name = item["anime_name"]
        db.media_id = item["media_id"]
        db.media_info_count_item_fans = item["media_info_count_item_fans"]
        db.media_info_count_item_play = item["media_info_count_item_play"]
        db.media_info_count_item_review = item["media_info_count_item_review"]
        db.long_comment = item['long_comment']
        db.short_comment = item["short_comment"]
        db.media_tags = "|".join(item["media_tags"])
        db.order = item["order"]
        db.score_all_people = item["score_all_people"]
        db.score = item["score"]
        try:
            session.add(db)
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()
        return item
